package cetcbigdata.da.personal_service.xinjiang;

import cetcbigdata.da.base.Base;
import com.alibaba.datax.common.plugin.RecordSender;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

import static cetcbigdata.da.personal_service.xinjiang.XJpersonUtil.*;

public class XJpersonal extends Base {

    private String dataUrl;
    private String dataResponse;

    @Override
    public void getData(RecordSender recordSender, List<Object> fieldsList) {

    }

    @Override
    public JSONObject getDataDemo() {
        try {
            //初始传入新疆维吾尔自治区的省级区域代码"650000"
            return this.traverseRegion("650000");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    //递归遍历所有地区
    private JSONObject traverseRegion(String areacode) {
        String url = "https://zwfw.xinjiang.gov.cn/xqldjkxt/rest/area/getAreaList";
        JSONObject parmas = JSONObject.parseObject("{'params':{'areacode':"+ areacode +"}}");
        String strResponse = postReq(url, parmas);
        JSONObject response = JSONObject.parseObject(strResponse);
        JSONObject custom = response.getJSONObject("custom");
        //区域划分
        //获取本级地区编码
        String nowarea_code = custom.getJSONObject("nowarea").getString("areacode");
        //获取当下区域划分
        JSONArray areatitlelist = custom.getJSONArray("areatitlelist");

        JSONArray arealist = custom.getJSONArray("arealist");
        if (null != arealist && arealist.size() > 0){
            for (Object o : arealist){
                JSONObject area = (JSONObject) o;
                traverseRegion(area.getString("areacode"));
//                return null;//====================注释可以拿多页数据，不注释只拿一页数据=======================================
            }
        }
        return getContent(nowarea_code, areatitlelist);
    }

    //获取服务事项详情页目录
    private JSONObject getContent(String areacode, JSONArray areatitlelist){

        //将当前区域划分获取到 region 中
        StringBuilder region = new StringBuilder();
        for (Object o : areatitlelist){
            JSONObject areatitle = (JSONObject) o;
            region.append("-").append(areatitle.getString("areaname"));
        }
        //删除最前的 "-"
        region.delete(0,1);

        try {
            String themeUrl = "https://zwfw.xinjiang.gov.cn/xjzwdt/rest/theme/listThemeByType";
            String text = "{'token':'Epoint_WebSerivce_**##0601','params':{" +
                    "'areacode':'"+areacode+"'," +
                    "'type':'1'}}";
            JSONObject themeParams = JSONObject.parseObject(text);
            //获取全部主题
            String strThemeResponse = postReq(themeUrl, themeParams);
            JSONArray themes = JSONObject.parseObject(strThemeResponse).getJSONObject("custom").getJSONArray("themelist");
            if (null != themes && themes.size() > 0){
                //遍历主题
                for (Object o : themes){
                    JSONObject theme = (JSONObject) o;

                    //获取主题名称到 module
                    String module ="个人服务-" + theme.getString("text");

                    //当前页
                    int currentpage = 0;
                    //总页数
                    int pags = -1;
                    //每页上限
                    int pagesize = 15;
                    while (currentpage != pags) {
                        String listUrl = "https://zwfw.xinjiang.gov.cn/xjzwdt/rest/task/getywTask";
                        text = "{'token':'Epoint_WebSerivce_**##0601','params':{" +
                                "'areacode':'"+areacode+"'," +
                                "'code':'"+theme.getString("code")+"'," +
                                "'currentpage':"+currentpage+"," +
                                "'pagesize':"+pagesize+"," +
                                "'category':'1'," +
                                "'taskname':''," +
                                "'tasktype':''," +
                                "'handletype':''," +
                                "'general':'general'}}";
                        JSONObject listParams = JSONObject.parseObject(text);
                        String listStrResponse = postReq(listUrl,listParams);
                        //获取列表页
                        JSONObject listResponse = JSONObject.parseObject(listStrResponse);
                        JSONArray catalogs = listResponse.getJSONObject("custom").getJSONArray("catalogs");
                        for (Object o1 : catalogs){
                            JSONObject catalog = (JSONObject) o1;

                            JSONArray tasklist = catalog.getJSONArray("tasklist");
                            for (Object o2 : tasklist){
                                JSONObject task = (JSONObject) o2;

                                dataUrl = null;
                                dataResponse = null;

                                JSONObject result = new JSONObject();
                                String taskcode = task.getString("taskcode");
                                if (null != task.getJSONArray("tasks") && task.getJSONArray("tasks").size() > 0){
                                    //事务下嵌套多项事务
                                    String ywCatalog_url = "https://zwfw.xinjiang.gov.cn/xjzwdt/rest/task/getywCatalogBasicInfo";
                                    text = "{'token':'Epoint_WebSerivce_**##0601','params':{" +
                                            "'areacode':'"+areacode+"'," +
                                            "'taskcode':'"+taskcode+"'," +
                                            "'type':'1'}}";
                                    JSONObject ywCatalog_params = JSONObject.parseObject(text);
                                    String ywCatalog_strResponse = postReq(ywCatalog_url,ywCatalog_params);
                                    //获取事务列表和列表信息
                                    JSONObject ywCatalog_response = JSONObject.parseObject(ywCatalog_strResponse);
                                    JSONObject catalogInfo = ywCatalog_response.getJSONObject("custom").getJSONObject("catalogInfo");
                                    //封装嵌套多事务的事务的详情页信息
                                    result.put("名称", catalogInfo.getString("taskname"));
                                    result.put("地址", "https://zwfw.xinjiang.gov.cn/xjzwfw2021/listDetailsnew.html?taskcode="+taskcode+"&type=1");
                                    result.put("类型", catalogInfo.getString("tasktype"));
                                    result.put("事项编码", catalogInfo.getString("taskcode"));
                                    result.put("行使主体", catalogInfo.getString("deptname"));
                                    result.put("行使层级", catalogInfo.getString("uselevel"));
                                    try {
                                        JSONArray bylawList = new JSONArray();
                                        for (Object o3 : ywCatalog_response.getJSONArray("bylaw")) {
                                            JSONObject data = (JSONObject) o3;
                                            JSONObject bylawValue = new JSONObject();
                                            bylawValue.put("法律法规名称", data.getString("lawname"));
                                            bylawValue.put("依据文号", data.getString("accordingnumber"));
                                            bylawValue.put("条款号", data.getString("termsnumber"));
                                            bylawValue.put("条款内容", data.getString("termscontent"));
                                            bylawList.add(bylawValue);
                                        }
                                        result.put("设立依据", bylawList);
                                    } catch (Exception e) {
                                        result.put("设立依据", null);
                                    }

                                    try {
                                        JSONArray taskBasInfo_list = new JSONArray();
                                        for (Object o3 : catalogInfo.getJSONArray("tasks")){
                                            //遍历事务列表
                                            JSONObject data = (JSONObject) o3;
                                            //获取事务详情页信息
                                            taskBasInfo_list.add(getTaskBasicInfo(areacode, data.getString("taskcode")));
                                        }
                                        result.put("选项", taskBasInfo_list);
                                    } catch (Exception e) {
                                        result.put("选项", null);
                                    }

                                    //将嵌套多事务的事务的详情页访问地址
                                    dataUrl = "https://zwfw.xinjiang.gov.cn/xjzwfw2021/listDetailsnew.html?taskcode="+taskcode+"&type=1";
                                    //将嵌套多事务的事务的详情页数据返回结果
                                    dataResponse = ywCatalog_strResponse;

                                }else {
                                    //事务下无嵌套多项事务
                                    //直接获取事务详情页信息
                                    result = getTaskBasicInfo(areacode, taskcode);
                                }
                                //测试用代码
                                System.out.println(
                                        "dataUrl:" + dataUrl + "\n" +
                                        "region:" + region+ "\n" +
                                        "module:" + module + "\n" +
                                        result + "\n"
                                );
                                return processResult(
                                        null,
                                        listStrResponse,
                                        dataUrl,
                                        dataResponse,
                                        result,
                                        region.toString(),
                                        module
                                );
                            }
                        }
                        //总条数
                        int totalcount = listResponse.getJSONObject("custom").getInteger("totalcount");
                        //更新总页数
                        pags = (int) Math.ceil((double) totalcount/pagesize);
                        //更新当前页
                        currentpage++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //单一事务详情页信息
    private JSONObject getTaskBasicInfo (String areacode, String taskcode) {
        JSONObject result = new JSONObject();
        String url = "https://zwfw.xinjiang.gov.cn/xjzwdt/rest/task/getTaskBasicInfo";
        String text = "{'token':'Epoint_WebSerivce_**##0601','params':{'taskcode':'"+taskcode+"','areacode':'"+areacode+"','accountguid':''}}";
        JSONObject params = JSONObject.parseObject(text);
        String response = postReq(url,params);
        JSONObject custom = JSONObject.parseObject(response).getJSONObject("custom");

        if (dataUrl == null) {
            //dataurl == null 表示不是被嵌套的单一事务
            //单一事务详情页访问地址
            dataUrl = "https://zwfw.xinjiang.gov.cn/bmfwtest/guidetest/guidance.html?taskcode="+taskcode;
            //单一事务详情页数据返回结果
            dataResponse = response;
        }

        //================================详情页信息================================
        result.put("名称", custom.getJSONObject("basic").getString("taskname"));

        result.put("地址", "https://zwfw.xinjiang.gov.cn/bmfwtest/guidetest/guidance.html?taskcode="+taskcode);

        result.put("基本信息", getBasicInfo(custom));//已完成

        result.put("受理条件", custom.getJSONObject("extend").getString("acceptcondition"));//已完成

        result.put("办理材料", getMaterials(custom.getJSONObject("extend").getJSONArray("materialscase")));//已完成

        result.put("办理流程", getFlowLCs(custom));//已完成

        result.put("收费标准", getFeeProject(custom.getJSONObject("extend").getJSONArray("feeproject")));//已完成

        result.put("设定依据", getbylaw(custom.getJSONObject("extend").getJSONArray("bylaw")));//已完成

        result.put("常见问题", getquestion(custom.getJSONArray("questions")));//已完成

        return result;
    }

    public static void main(String[] args) {
        XJpersonal xJpersonal = new XJpersonal();
        xJpersonal.getDataDemo();
    }
}
